/**
 * 
 */
package com.thoughtworks.merchantsguide.processor;

import java.text.MessageFormat;

import org.apache.commons.lang.StringUtils;

import com.thoughtworks.merchantsguide.cache.ComodityPriceCache;
import com.thoughtworks.merchantsguide.commodity.Matter;
import com.thoughtworks.merchantsguide.common.Utility;
import com.thoughtworks.merchantsguide.converter.GalicticToRomanConverter;
import com.thoughtworks.merchantsguide.converter.RomanToArabicConverter;
import com.thoughtworks.merchantsguide.exception.InvalidCommodityException;
import com.thoughtworks.merchantsguide.exception.UnsupportedNumberException;
import com.thoughtworks.merchantsguide.service.PriceService;

/**
 * This processor, services the customer query.
 *
 */
public class CustomerQueryProcessor implements LineProcessor {

	private static String startLiteral = " is ";
	private static String endLiteral = " ?";

	private static final String COMMODITY_PRICE_MESSAGE = "{1} is {2}";

	/**
	 * @throws UnsupportedNumberException
	 * @throws InvalidCommodityException
	 * @throws Exception
	 * @see com.thoughtworks.merchantsguide.processor.LineProcessor#process(java.lang.String)
	 */
	@Override
	public Object process(String query) throws UnsupportedNumberException, InvalidCommodityException {

		String evaluationResult = "";
		int beginIndex = query.indexOf(startLiteral);
		String evaluationString = query.substring(beginIndex + startLiteral.length(), query.length() - endLiteral.length());
		// First to check if the query contains Commodity or not.
		// If only to check the galactic to arabic conversion, we check if
		// " much " string is present in the query.
		if (StringUtils.contains(query, " much ")) {
			String romanEq = new GalicticToRomanConverter().convert(evaluationString);
			evaluationResult = String.valueOf(new RomanToArabicConverter().convert(romanEq));
		} else {
			int lastIndexOfSpace = evaluationString.lastIndexOf(SPACE_FOR_SEARCH);
			long quantity = Utility.getArabicFromGalacticNumber(evaluationString.substring(0, lastIndexOfSpace));
			String matterName = evaluationString.substring(lastIndexOfSpace + 1);
			if (ComodityPriceCache.isSupportedMatter(matterName)) {
				Matter matter = ComodityPriceCache.getMatterForName(matterName);
				evaluationResult = new PriceService().getPrice(matter, quantity) + " Credits";
			}
		}
		return MessageFormat.format(COMMODITY_PRICE_MESSAGE, new StringBuilder(), evaluationString, evaluationResult);
	}

}
